﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KingRoad.EPM.Web.Areas.PersonnelLog.ViewModels;
using KingRoad.EPM.PersonnelLogEntity.Model;
using KingRoad.EPM.Web.Areas.PersonnelLog.PersonnelLogFramework.Common;
using System.IO;
using System.Data;

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System.Text;
using NPOI.SS.Util;

namespace KingRoad.EPM.Web.Areas.PersonnelLog.Controllers
{
    public class PlmPersonLeaveController : BaseController
    {
        /// <summary>
        /// 请假管理-列表 rygl_qjgl
        /// </summary>
        /// <returns></returns>
        public ActionResult PersonLeaveList(string pageName)
        {
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = 1;
            //每页多少条
            ViewBag.numPerPage = 20;
            var list = PlmPersonleaveUIRule.GetListForPage(ViewBag.pageNum, ViewBag.numPerPage, "Pl_Time", out totalRecord, " Pl_Section in (" + Get_JL_JC_ZDJL_SG_SegmentCodes() + ") ");
            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            //   return View(new PlmPersonLeaveViewModel { PersonleaveList = list });
            return String.IsNullOrEmpty(pageName) ? View(new PlmPersonLeaveViewModel { PersonleaveList = list }) : View(pageName, new PlmPersonLeaveViewModel { PersonleaveList = list });


        }
        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="vm"></param>
        /// <returns></returns>
        public ActionResult SplitPage(PlmPersonLeaveViewModel vm)
        {
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = Convert.ToInt32(Request.Form["pageNum"]);
            //每页多少条
            ViewBag.numPerPage = Convert.ToInt32(Request.Form["numPerPage"]);
            if (ViewBag.pageNum == 0 || ViewBag.numPerPage == 0)
                return PersonLeaveList("PersonLeaveList");


            ViewBag.name = Request.Form["name"];
            ViewBag.time = Request.Form["time"];
            ViewBag.section = Request.Form["section"];

            string sql = " Pl_Section in (" + Get_JL_JC_ZDJL_SG_SegmentCodes() + ") ";
            if (ViewBag.time != "")
                sql += " and convert( char(10), Pl_Time, 120 ) ='" + ViewBag.time + "' ";
            if (ViewBag.section != "")
                sql += " and Pl_Section like '%" + ViewBag.section + "%' ";
            if (ViewBag.name != "")
                sql += " and Pl_PersonName like '%" + ViewBag.name + "%' or Pl_CoverMan like '%" + ViewBag.name + "%' ";
            var list = PlmPersonleaveUIRule.GetListForPage(ViewBag.pageNum, ViewBag.numPerPage, "Pl_Time", out totalRecord, sql);
            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            return View("PersonLeaveList", new PlmPersonLeaveViewModel { PersonleaveList = list });
        }

        /// <summary>
        /// 请假管理-添加 
        /// 功能：显示添加页面
        /// </summary>
        /// <returns></returns>
        public ActionResult PersonLeaveAdd()
        {
            List<ProjectUnitInfo> unitList = GetUnitListByType(0);
            return View(new PlmPersonLeaveViewModel { TheUnitList = unitList });
        }
        /// <summary>
        /// 请假管理-添加 
        /// 功能：执行添加操作
        /// </summary>
        /// <returns></returns>
        public JsonResult PersonLeaveAddData(PlmPersonLeaveViewModel vm)
        {
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                vm.PersonleaveInfo.Pl_ID = Guid.NewGuid().ToString();
                //TODO:登录人信息
                vm.PersonleaveInfo.Pl_UserID = GetLoginUserId;//登录人ID
                vm.PersonleaveInfo.Pl_UserName = GetLoginUserRealName; //登录人名称
                vm.PersonleaveInfo.Pl_UnitID = GetLoginUserDepartmentId;//登录人所属部门id
                vm.PersonleaveInfo.Pl_UnitName = GetLoginUserDepartmentName;//登录人所属部门
                //vm.PersonleaveInfo.Pl_Time = DateTime.Now;
                bool info = PlmPersonleaveUIRule.InsertEntity(vm.PersonleaveInfo);
            });

            dynamic jsonReturn = new ExpandoObject();

            //保存成功
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "添加成功",
                    navTabId = "PersonnelLog.PlmPersonLeave.PersonLeaveList",
                    rel = "",
                    callbackType = "closeCurrent",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "添加失败",
                };
            }

            return new JsonResult()
            {
                Data = jsonReturn
            };
        }

        /// <summary>
        /// 请假管理——编辑
        /// 功能：根据id加载相对应数据
        /// </summary>
        /// <returns></returns>
        public ActionResult PersonLeaveEdit(Guid id)
        {
            var info = PlmPersonleaveUIRule.GetInfoByID(id);
            var unitList = GetUnitListByType(0);
            info.Pl_UserID = GetLoginUserId;//登录人ID
            info.Pl_UserName = GetLoginUserRealName; //登录人名称
            info.Pl_Time = DateTime.Now;
            return View(new PlmPersonLeaveViewModel { PersonleaveInfo = info, TheUnitList = unitList });
        }
        /// <summary>
        /// 请假管理-编辑（保存工作） 
        /// 功能：执行保存数据
        /// </summary>
        /// <returns></returns>
        public JsonResult PersonLeaveEditData(PlmPersonLeaveViewModel vm)
        {
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                //vm.PersonleaveInfo.Pl_Time = DateTime.Now;
                //TODO:登录人信息
                vm.PersonleaveInfo.Pl_UserID = GetLoginUserId;//登录人ID
                vm.PersonleaveInfo.Pl_UserName = GetLoginUserRealName; //登录人名称
                vm.PersonleaveInfo.Pl_UnitID = GetLoginUserDepartmentId;//登录人所属部门id
                vm.PersonleaveInfo.Pl_UnitName = GetLoginUserDepartmentName;//登录人所属部门
                //vm.PersonleaveInfo.Pl_Time = DateTime.Now;
                bool info = PlmPersonleaveUIRule.UpdateEntity(vm.PersonleaveInfo);
            });

            dynamic jsonReturn = new ExpandoObject();

            //保存成功
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "更新成功",
                    navTabId = "PersonnelLog.PlmPersonLeave.PersonLeaveList",
                    rel = "",
                    callbackType = "closeCurrent",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "更新失败",
                };
            }

            return new JsonResult()
            {
                Data = jsonReturn
            };
        }
        /// <summary>
        /// 请假管理——查看
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns>
        public ActionResult PersonLeaveDetail(Guid id)
        {
            var model = new PlmPersonLeaveViewModel();
            model.PersonleaveInfo = PlmPersonleaveUIRule.GetInfoByID(id);
            model.TheAuditList = ScmAuditUIRule.GetAuditListByPID(id.ToString());
            model.TheAuditList.Remove(model.TheAuditList.Where(p => p.A_State == 0).FirstOrDefault());
            return View(model);
        }
        /// <summary>
        /// 请假管理——查看  审批流程图
        /// </summary>
        /// <returns></returns>
        public ActionResult ApprovalProcessImage(string type, string state)
        {
            ViewBag.ImageLc = type + state;
            return View();
        }
        /// <summary>
        /// 请假管理-批量删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult PersonLeaveMultiDelete(string id)
        {
            dynamic jsonReturn = new ExpandoObject();
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                bool info = PlmPersonleaveUIRule.DeleteEntityByMultiStringID(id);
            });

            //保存成功
            if (true)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "删除成功",
                    navTabId = "PersonnelLog.PlmPersonLeave.PersonLeaveList",
                    rel = "",
                    callbackType = "",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "删除失败",
                };
            }
            return new JsonResult()
            {
                Data = jsonReturn
            };
        }

        /// <summary>
        /// 选择人员弹出框
        /// </summary>
        /// <param name="flag"></param>
        /// <param name="section"></param>
        /// <returns></returns>
        public ActionResult PersonnelList(string flag, string section)
        {
            ViewBag.flag = flag;
            ViewBag.section = section;
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = 1;
            //每页多少条
            ViewBag.numPerPage = 20;
            var consPersonnelList = PlmPersonnelinfoUIRule.GetAllCostplanmainForPage(ViewBag.pageNum, ViewBag.numPerPage, "Pi_Num", out totalRecord, "Pi_SectionName ='" + section + "' ");
            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            return View(new PlmPersonnelinfoViewModel { ThePersonnelinfoList = consPersonnelList });
        }

        /// <summary>
        /// 选择人员弹出框分页
        /// </summary>
        /// <param name="vm"></param>
        /// <returns></returns>
        public ActionResult SplitPageForPersonnel(PlmPersonnelinfoViewModel vm)
        {
            ViewBag.flag = Request.Form["flag"];
            ViewBag.section = Request.Form["section"]; ;
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = Convert.ToInt32(Request.Form["pageNum"]);
            //每页多少条
            ViewBag.numPerPage = Convert.ToInt32(Request.Form["numPerPage"]);

            ViewBag.iput_name = Request.Form["iput_name"];


            string sql = " 1=1 ";

            if (ViewBag.iput_name != "")
                sql += " and Pi_Name like '%" + ViewBag.iput_name + "%' ";
            sql += " and Pi_SectionName ='" + ViewBag.section + "' ";
            var list = PlmPersonnelinfoUIRule.GetAllCostplanmainForPage(ViewBag.pageNum, ViewBag.numPerPage, "Pi_Num", out totalRecord, sql);
            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            return View("PersonnelList", new PlmPersonnelinfoViewModel { ThePersonnelinfoList = list });
        }


        /// <summary>
        /// 请假管理-审批列表 
        /// </summary>
        /// <returns></returns>
        public ActionResult PersonLeaveCheckList(string pageName)
        {
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = 1;
            //每页多少条
            ViewBag.numPerPage = 20;
            //根据当前登录人 加载审批列表   审批状态(0=草稿，1=驻地/检测主任审批，2=总监审批，3=质监部部长批示，4=主管领导批示，5=审批通过，6=审批不通过)
            string sql = " Pl_Section in (" + Get_JL_JC_ZDJL_SG_SegmentCodes() + ") ";
            string code = GetLoginUserInfo.WorkgroupCode;
            switch (code)
            {
                case "zdjlgcs"://驻地监理工程师
                    sql += " and Pl_State=1 ";
                    break;
                case "syszr"://中心试验室主任
                    sql += " and Pl_State=1 ";
                    break;
                case "zjlgcs"://总监理工程师
                    sql += " and Pl_State=2 ";
                    break;
                case "yzzjbz"://质监部长
                    sql += " and Pl_State=3 ";
                    break;
                case "yzld"://业主领导
                    sql += " and Pl_State=4 ";
                    break;
                case "yzzjl"://业主总经理
                    sql += " and Pl_State=4 ";
                    break;
                case "yzzgb"://业主总工办
                    sql += " and Pl_State=4 ";
                    break;
                case "yzdsz"://业主董事长
                    sql += " and Pl_State=4 ";
                    break;
                default:
                    sql += " and Pl_State=4444444 ";
                    break;
            }
            var list = PlmPersonleaveUIRule.GetListForPage(ViewBag.pageNum, ViewBag.numPerPage, "Pl_Time", out totalRecord, sql);
            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            return String.IsNullOrEmpty(pageName) ? View(new PlmPersonLeaveViewModel { PersonleaveList = list }) : View(pageName, new PlmPersonLeaveViewModel { PersonleaveList = list });
        }
        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="vm"></param>
        /// <returns></returns>
        public ActionResult CheckSplitPage()
        {
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = Convert.ToInt32(Request.Form["pageNum"]);
            //每页多少条
            ViewBag.numPerPage = Convert.ToInt32(Request.Form["numPerPage"]);
            if (ViewBag.pageNum == 0 || ViewBag.numPerPage == 0)
                return PersonLeaveCheckList("PersonLeaveCheckList");
            ViewBag.name = Request.Form["name"];
            ViewBag.time = Request.Form["time"];
            ViewBag.section = Request.Form["section"];

            //根据当前登录人 加载审批列表   审批状态(0=草稿，1=驻地/检测主任审批，2=总监审批，3=质监部部长批示，4=主管领导批示，5=审批通过，6=审批不通过)
            string sql = " Pl_Section in (" + Get_JL_JC_ZDJL_SG_SegmentCodes() + ") ";
            string code = GetLoginUserInfo.WorkgroupCode;
            switch (code)
            {
                case "zdjlgcs"://驻地监理工程师
                    sql += " and Pl_State=1 ";
                    break;
                case "syszr"://中心试验室主任
                    sql += " and Pl_State=1 ";
                    break;
                case "zjlgcs"://总监理工程师
                    sql += " and Pl_State=2 ";
                    break;
                case "yzzjbz"://质监部长
                    sql += " and Pl_State=3 ";
                    break;
                case "yzld"://业主领导
                    sql += " and Pl_State=4 ";
                    break;
                case "yzzjl"://业主总经理
                    sql += " and Pl_State=4 ";
                    break;
                case "yzzgb"://业主总工办
                    sql += " and Pl_State=4 ";
                    break;
                case "yzdsz"://业主董事长
                    sql += " and Pl_State=4 ";
                    break;
                default:
                    sql += " and Pl_State=4444444 ";
                    break;
            }
            if (ViewBag.time != "")
                sql += " and convert( char(10), Pl_Time, 120 ) ='" + ViewBag.time + "' ";
            if (ViewBag.section != "")
                sql += " and Pl_Section like '%" + ViewBag.section + "%' ";
            if (ViewBag.name != "")
                sql += " and (Pl_PersonName like '%" + ViewBag.name + "%' or Pl_CoverMan like '%" + ViewBag.name + "%') ";
            var list = PlmPersonleaveUIRule.GetListForPage(ViewBag.pageNum, ViewBag.numPerPage, "Pl_Time", out totalRecord, sql);
            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            return View("PersonLeaveCheckList", new PlmPersonLeaveViewModel { PersonleaveList = list });
        }
        /// <summary>
        /// 请假审批
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult PersonLeaveAudit(Guid id)
        {
            PlmPersonleaveInfo info = PlmPersonleaveUIRule.GetInfoByID(id);
            var model = new PlmPersonLeaveViewModel();
            model.TheAuditInfo = new ScmAuditInfo();
            model.TheAuditInfo.A_ID = Guid.NewGuid().ToString();
            model.TheAuditInfo.A_PrimayID = id.ToString();
            model.TheAuditInfo.A_Time = DateTime.Now;
            model.TheAuditInfo.A_IsApproved = true;
            model.TheAuditInfo.A_State = info.Pl_State;
            //当前登陆人信息
            model.TheAuditInfo.A_DepID = GetLoginUserDepartmentId;
            model.TheAuditInfo.A_DepName = GetLoginUserInfo.WorkgroupFullName;
            model.TheAuditInfo.A_ManID = GetLoginUserId;
            model.TheAuditInfo.A_ManName = GetLoginUserRealName;

            List<SelectListItem> listState = new List<SelectListItem>();
            if (info.Pl_State == 0)
                listState.Add(new SelectListItem { Text = "上报", Value = "true" });
            else
            {
                listState.Add(new SelectListItem { Text = "审批通过", Value = "true" });
                listState.Add(new SelectListItem { Text = "审批不通过", Value = "false" });
            }
            ViewBag.State = info.Pl_State;
            ViewBag.listState = listState;
            return View(model);
        }
        /// <summary>
        /// 请假审批—提交
        /// </summary>
        /// <param name="vm"></param>
        /// <returns></returns>
        public JsonResult SaveCheckResult(PlmPersonLeaveViewModel model)
        {
            var aInfo = model.TheAuditInfo;
            PlmPersonleaveInfo info = PlmPersonleaveUIRule.GetInfoByID(new Guid(aInfo.A_PrimayID));
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                //审批状态 state (0=草稿，1=驻地/检测主任审批，2=总监审批，3=质监部部长批示，4=主管领导批示，5=审批通过，6=审批不通过)
                int state = 0;
                if (aInfo.A_IsApproved == false)
                    state = 6;
                else
                {
                    //info.Pl_Type 请假类型（0=员工请假，1=主任请假） 
                    if (info.Pl_Type == false)
                    {
                        switch (info.Pl_State)
                        {
                            case 0:
                                {
                                    //判断请假人是否是总监办人员
                                    PlmPersonnelinfoInfo pinfo=PlmPersonnelinfoUIRule.GetPersonnelinfoByID(new Guid(info.Pl_PersonID));
                                    if (pinfo.Pi_SectionName.IndexOf("ZJ") >= 0)
                                        state = 2;
                                    else
                                        state = 1;
                                }
                                break;
                            case 1:
                                state = 2;
                                break;
                            case 2:
                                state = 5;
                                break;
                            default:
                                break;
                        }
                    }
                    else
                    {
                        switch (info.Pl_State)
                        {
                            case 0:
                                state = 2;
                                break;
                            case 2:
                                state = 3;
                                break;
                            case 3:
                                state = 4;
                                break;
                            case 4:
                                state = 5;
                                break;
                            default:
                                break;
                        }
                    }
                }
                ScmAuditUIRule.AddAudit(aInfo, 2, state);
            });
            dynamic jsonReturn = new ExpandoObject();

            //保存成功
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "审批成功",
                    navTabId = "PersonnelLog.PlmPersonLeave.PersonLeaveCheckList",
                    rel = "",
                    callbackType = "closeCurrent",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "审批失败",
                };
            }

            return new JsonResult()
            {
                Data = jsonReturn
            };
        }
    }
}
